﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Id;
using NHibernate.Engine;
using NHibernate.Dialect;
using NHibernate.Type;
using NHibernate;
using Common;
using Basic.Model.Entity;
using Basic.Model.EntityManager;

namespace Basic
{
    public class PKGenerator : IIdentifierGenerator, IConfigurable
    {
        private string tableName;

        public object Generate(ISessionImplementor session, object obj)
        {
            bool isSQLite = session.Factory.Dialect is SQLiteDialect;
            int rtn = 0;
            if (isSQLite)
            {
                ISession s = session.GetSession();
                AutoNumber an = AutoNumberManager.GetAutoNumberByTableName(s, tableName);
                if (an == null)
                    throw new IdentifierGenerationException("在获取自动编号时查找不到表" + tableName + "的记录");
                rtn = an.currentNum;
                an.currentNum++;
            }
            else
            {
                ISession s = null;
                ITransaction trans = null;
                try
                {
                    s = session.Factory.OpenSession();
                    trans = s.BeginTransaction();
                    AutoNumber an = AutoNumberManager.GetAutoNumberByTableName(s, tableName);
                    if (an == null)
                        throw new IdentifierGenerationException("在获取自动编号时查找不到表" + tableName + "的记录");
                    rtn = an.currentNum;
                    an.currentNum++;
                    trans.Commit();
                }
                catch
                {
                    if (trans != null)
                        trans.Rollback();
                    throw;
                }
                finally
                {
                    if (s != null)
                        s.Close();
                }

            }

            return rtn;
        }
        public void Configure(IType type, IDictionary<string, string> parms, NHibernate.Dialect.Dialect d)
        {
            tableName = parms["table-name"];
        }
    }
}
